package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneCommonService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DateFormatUtils;
import com.iwhalecloud.bss.kite.cucc.common.util.DateUtils;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.base.util.LocalAttrUtils;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.zsmart.core.util.DateUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 20220222version版本AZ端要求完成时间
 **/
@Service
public class AZRequiredCompleteTimeHandler extends AbstractAttrHandler {

    @Autowired
    private IQuerySceneInstService querySceneInstService;
    @Autowired
    private IOperateSceneCommonService operateSceneCommonService;
    @Override
    public void init(CommonAttrVO commonAttr) {
        String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        String custId = KiteWebContext.getContext().getCust().getCustId();
        KiteAttr attr =querySceneInstService.getCommonAttr(sceneInstId, commonAttr.getFieldName());
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(sceneInstId);
        KiteProdInst prodInst = querySceneInstService.listProdInstsFromOfferInst(KiteWebContext.getContext().getCustId(), kiteSceneInst.getRootInstId()).stream()
            .filter(inst -> !KiteStringUtils.equalsAny(inst.getActionType().name(), ActionType.X.name(), ActionType.D.name()))
            .findFirst().orElse(null);
            String productId = prodInst.getProdId();
            if (KiteStringUtils.isEmpty(attr.getValue())) {
                String serviceOfferId =kiteSceneInst.getServiceOfferId();
//                crossDomain(sceneInstId,serviceOfferId,commonAttr,attr,productId);
                nonCrossDomain(commonAttr,attr,productId);
            }
        setCommonAttr(commonAttr);
        operateSceneCommonService.setCommonAttr(sceneInstId, attr);
    }

    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {
        //重提初始化不校验
        //fixme 可能导致频繁访问缓存,上线临时处理方案
        Map<String, Object> extParams = ContextUtil.getLoginInfo().getUserInfo().getExtParams();
        if (Objects.nonNull(extParams)&& extParams.containsKey("nodeCode")) {
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }
        // 是否为页面初始化渲染，是（T），跳过校验
        String isInitPageRenderFlag = querySceneInstService.getExtParameterValue(sceneInstId, "isInitPageRenderFlag");
        if (KeyConsts.IFTRUE_T.equals(isInitPageRenderFlag)) {
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }
        if (KiteStringUtils.isEmpty(value)){
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }
        String allCompleteTimePattern = DateFormatUtils.DATE_TIME_FORMAT;
        Date complateDate = null;
        try{
            complateDate = DateUtils.parseStrToDate(value, LocalAttrUtils.FormatByValue(value));
        }catch (Exception e){
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("日期转换异常");
        }
        //A、Z端要求完成时间 不能早于当前时间
        if (null != complateDate && DateUtil.compare(DateFormatUtils.getCurrentDate(),complateDate) >1){
            BssException.throwOut(KeyConsts.LOG_MODULE, "", "要求完成时间不能早于当前时间");
        }
        //全程要求完成时间
        Date allCompleteDate = null;
        String allCompleteTimeStr = querySceneInstService.getCommonAttrValue(sceneInstId, "ORD10012");
        if(KiteStringUtils.isNotEmpty(allCompleteTimeStr)){
            try{
                allCompleteDate = DateUtils.parseStrToDate(allCompleteTimeStr, allCompleteTimePattern.substring(0,allCompleteTimeStr.length()));
            }catch(Exception e){
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("日期转换异常");
            }
            //A、Z端要求完成时间 不能晚于全程要求完成时间
            if (null != complateDate && DateUtil.compare(complateDate,allCompleteDate) >1){
                BssException.throwOut(KeyConsts.LOG_MODULE, "", "A、Z端要求完成时间不能晚于全程要求完成时间");
            }
        }
        return super.apply(sceneInstId, fieldName, value, valueDesc);
    }

    private void crossDomain(String sceneInstId,String serviceOfferId,CommonAttrVO commonAttr,KiteAttr attr,String productId){
        Map<String, Object> extParams = ContextUtil.getLoginInfo().getUserInfo().getExtParams();
        String nodeCode = StringUtils.EMPTY;
        if (Objects.nonNull(extParams)&& extParams.containsKey("nodeCode")) {
            nodeCode = KiteMapUtils.getString(extParams,"nodeCode");
        }else {
            nodeCode = querySceneInstService.getExtParameterValue(sceneInstId, "nodeCode");
        }
        String BIZ_TYPE = MapUtils.getString(this.querySceneInstService.getExtParameter(sceneInstId),"serviceOfferId");
        String value =attr.getValue();
            if(KiteStringUtils.isEmpty(attr.getDefaultValue())) {
                if (KiteStringUtils.equalsAny(LocalServiceOfferConsts.SERVICE_OFFER_RESOURCE_CHECK,serviceOfferId,BIZ_TYPE)) {
                    //核查重提
                    if ("OrderResubmit".equals(nodeCode)) {
                        value = LocalAttrUtils.compareDate(commonAttr, productId,null);
                        attr.setValue(value);
                        attr.setDefaultValue(value);
                    } else {
                        value = LocalAttrUtils.getInstance().AZOffsetDay(productId, null,null);
                        attr.setDefaultValue(value);
                    }
                    attr.setValue(value);
                    commonAttr.setValue(value);
                    commonAttr.setValueDesc(value);
                    commonAttr.setDefaultValue(value);
                }else{
                    nonCrossDomain(commonAttr,attr,productId);
                }
            }
            value = attr.getValue();
            // 订单补录情况，来单属性为空时，不设置默认值，否则会有展示属性值与甩单填写不一致情况
            if(KiteStringUtils.isEmpty(value) &&!KiteStringUtils.isEmpty(attr.getDefaultValue())&& !KiteStringUtils.isEqual(nodeCode, "OrderAddRecord")){
                attr.setValue(attr.getDefaultValue());
                attr.setValueDesc(attr.getDefaultValue());
            }
        }
    private void nonCrossDomain(CommonAttrVO commonAttr,KiteAttr attr,String productId){
        LocalDateTime nowDate = LocalDateTime.now();
        // 追加天数
        String value = nowDate.plusDays(getAddDays(productId)).toString(DateFormatUtils.DATE_MINUTE_FORMAT);
        attr.setValue(value);
        attr.setValueDesc(value);
        attr.setDefaultValue(value);
        commonAttr.setValue(value);
        commonAttr.setValueDesc(value);
        commonAttr.setDefaultValue(value);
    }
    /**
     * 不同产品默认 当日往后加天数getAddDays
     */
    private static int getAddDays(String productId) {
        int result = 3;
        switch (productId) {
            case "10003665":
                result = 5;
                break;
            case "50041909":
                result = 5;
                break;
            default:
                break;
        }
        return result;
    }
}
